//
//  ZQUserAccountViewModel.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/15.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

class ZQUserAccountViewModel: NSObject {
    
    //引入视图模型
    var userAccount : ZQUserAccount?
    
    //单利对象
    static let shared: ZQUserAccountViewModel = ZQUserAccountViewModel()
    
    
    //重写构造函数
    //在用户已经登录的情况下给模型赋值
    override init() {
        
        super.init()
        //保证以后再判断是否登录的时候 不在访问磁盘
        //将磁盘数据保存在内存中
        userAccount = self.loadUserAccount()
        
    }
    
    //增加一个头像属性
    var headURL : URL?{
        
        return URL(string: userAccount?.avatar_large ?? "")
    }
    //主页面用户请求To_ken
    
    var access_token : String?{
        
        return  userAccount?.access_token
        
    }
 
    //计算行属性
    var userLogin: Bool{
        
    //判断令牌是否过期~是否登陆
        if userAccount?.access_token != nil && isExpires == false{
              //已经登录了
            return true
        }
        //默认没有登录
        return false

    }


    //判断令牌是否过期
    var isExpires : Bool {
        
        
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            
            return false
        }
        
        return true
    }
 
  

    
    func loadaccessToken(code:String ,finished:@escaping (Bool) -> ()){
        //
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : "1943605865",
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        HMNetworkTools.shared.request(method: .POST, urlString: urlstring, parameters: parameters){ (responseObject, error) in
            
 
            
            if error != nil {
//                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                finished(false)
                
                return
            }
//            print(responseObject)
            //请求成功
            self.loaduserInfo(dict:responseObject as! [String : Any], userfinished: finished)
            
            //
        }
    }
    
       private func loaduserInfo(dict : [String : Any],userfinished:@escaping (Bool) -> ()){
        let userString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]
        
        let uid = dict["uid"]
        
        let parameters =  ["access_token" : token,"uid" : uid]
        
        HMNetworkTools.shared.request(method: .GET, urlString: userString, parameters: parameters) { (responseObject, error ) in
            if error != nil{
                
                userfinished(false)
//                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是有网,但是手机坏啦!")
                return
                
            }
           
            
            var userinfo = responseObject as! [String : Any]
            
            for (key,value) in dict{
                userinfo[key] = value
                
            }
            
            //需要userinfo转成模型对象,
            
            //用归档的方式存储自定义模型
            let userAccount = ZQUserAccount(dict: userinfo)
            print(userAccount)
            self.saveUserAccount(userAccount: userAccount)
            
            self.userAccount = userAccount
            
            //执行成功的回调
            userfinished(true)
//            let cacheaccount = self.loadUserAccount()
            //                print(cacheaccount)
            
        }
        
    }
    
    
    private func saveUserAccount(userAccount : ZQUserAccount){
        
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
        
    }
    
    
    private func loadUserAccount() -> ZQUserAccount? {
        
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
        if let userAccount = account as? ZQUserAccount {
            
            return userAccount
        }
        
        return nil
    }
    

    
    
    
}
